package com.lej.core.widget.customview.scaleview

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.LinearLayout
import androidx.appcompat.R
import androidx.appcompat.widget.AppCompatButton
import androidx.appcompat.widget.AppCompatImageView
import com.qmuiteam.qmui.layout.QMUIButton
import com.qmuiteam.qmui.layout.QMUILinearLayout

/**  触摸的时候缩放的按钮 */
class ScaleButton @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = R.attr.buttonStyle
) : AppCompatButton(context, attrs, defStyleAttr) {
    override fun dispatchSetPressed(pressed: Boolean) {
        super.dispatchSetPressed(pressed)
        dealScalePressed(pressed)
    }
}

class ScaleImageView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : AppCompatImageView(context, attrs, defStyleAttr) {
    override fun dispatchSetPressed(pressed: Boolean) {
        super.dispatchSetPressed(pressed)
        dealScalePressed(pressed)
    }
}
class ScaleLineaLayout @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
    /**宽高比例*/
    var ratio = 0f

    override fun dispatchSetPressed(pressed: Boolean) {
        super.dispatchSetPressed(pressed)
        dealScalePressed(pressed)
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        if (ratio == 0f) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        } else {
            val width = MeasureSpec.getSize(widthMeasureSpec)
            val hms = MeasureSpec.makeMeasureSpec(((width * ratio).toInt()), MeasureSpec.EXACTLY)
            super.onMeasure(widthMeasureSpec, hms)
        }
    }
}

class ScaleQMUILineaLayout @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : QMUILinearLayout(context, attrs, defStyleAttr) {
    override fun dispatchSetPressed(pressed: Boolean) {
        super.dispatchSetPressed(pressed)
        dealScalePressed(pressed)
    }
}
class ScaleQMUIButton @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : QMUIButton(context, attrs, defStyleAttr) {
    override fun dispatchSetPressed(pressed: Boolean) {
        super.dispatchSetPressed(pressed)
        dealScalePressed(pressed)
    }
}

private fun View.dealScalePressed(pressed: Boolean) {
    if (pressed && scaleX != 0.93f) {
        animate().scaleX(0.93f).scaleY(0.93f).setDuration(80).start()
    }
    if (!pressed && scaleX != 1f)
        animate().scaleX(1f).scaleY(1f).setDuration(80).start()
}